import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as path;

class FileUploadPage extends StatefulWidget {
  @override
  _FileUploadPageState createState() => _FileUploadPageState();
}

class _FileUploadPageState extends State<FileUploadPage> {
  final List<File> _files = [];

  void _addFile(File file) {
    // 检查文件是否已存在于列表中
    if (_files.any((existingFile) => existingFile.path == file.path)) {
      // 如果文件已存在，不添加新文件，并提示用户
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('文件已存在，未添加重复文件。')),
      );
    } else {
      // 如果文件不存在，添加到列表中
      setState(() {
        _files.add(file);
      });
    }
  }

  void _removeFile(File file) {
    setState(() {
      _files.remove(file);
    });
  }

  Future<void> _uploadFiles() async {
    if (_files.isEmpty) {
      return;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('File Upload Demo'),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: ListView.builder(
              itemCount: _files.length,
              itemBuilder: (context, index) {
                final file = _files[index];
                return ListTile(
                  title: Text(file.path,),//overflow: TextOverflow.ellipsis path.basename(file.path)
                  trailing: IconButton(
                    icon: const Icon(Icons.delete),
                    onPressed: () => _removeFile(file),
                  ),
                );
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: TextField(
                    decoration: const InputDecoration(
                      labelText: '选择文件',
                      border: OutlineInputBorder(),
                    ),
                    onTap: () async {
                      final result = await FilePicker.platform.pickFiles(type: FileType.any);

                      if (result != null && result.files.single.path != null) {
                        final file = File(result.files.single.path!);
                        _addFile(file);
                      }
                    },
                  ),
                ),
                const SizedBox(width: 16),
                ElevatedButton(
                  onPressed: _uploadFiles,
                  child: const Text('Upload'),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(home: FileUploadPage()));
}

// 需要安装file_picker包来实现文件选择
// 在pubspec.yaml中添加依赖
// dependencies:
//   file_picker: ^4.3.0